package com.api.smoke.tag;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.api.test.AbstractApiTest;
import com.api.test.VoidContextLoader;
import com.api.util.AssertUtil;
import com.api.util.DataUtil;
import com.api.util.GenericUtils.GenericType;
import com.api.util.repo.DtoFactory;
import com.api.util.repo.impl.DomainUser;
import com.zyncro.api.ITagApiService;
import com.zyncro.api.exceptions.ZyncroApiException;
import com.zyncro.api.model.PagedItemsResultApi;
import com.zyncro.api.model.TagApi;
import com.zyncro.api.model.TagApiType;

@ContextConfiguration(loader = VoidContextLoader.class)
public class GetTagsSmoke extends AbstractApiTest {

	private PagedItemsResultApi<TagApi> expectedResults;

	@BeforeClass
	protected void setUp() throws Exception {

		final String domainName = this.getClass().getSimpleName();
		DomainUser mainAdmin = getRepo().getMainUser(domainName);

		getApi().login(mainAdmin.getAppId(), mainAdmin.getPassword());

		String fileName = getRepo().getPropertyDto(domainName, new DtoFactory<String>() {

			public String createDto() {

				String env = System.getProperty("env");

				String fileName = String.format("./json/%s/%s.json", env, domainName);

				try {
					getApi().getService(ITagApiService.class).createTag("name1", TagApiType.CATEGORY);
					getApi().getService(ITagApiService.class).createTag("name2", TagApiType.LOCATION);

					PagedItemsResultApi<TagApi> result = getApi().getService(ITagApiService.class).getTags(null, 0, 0);

					DataUtil.saveDtoToFile(result, fileName);

				} catch (Exception e) {

					throw new IllegalStateException("Exception creating GetDepartments test data", e);
				}

				return fileName;
			}
		});

		this.expectedResults = DataUtil.getDtoFromFile(fileName, new GenericType<PagedItemsResultApi<TagApi>>() {
		});
	}

	@Test
	public void testGetTags() throws ZyncroApiException {

		TagApiType tagType = null;
		int pageNumber = 0;
		int itemsPerPage = 0;

		PagedItemsResultApi<TagApi> result = getApi().getService(ITagApiService.class).getTags(tagType, pageNumber, itemsPerPage);

		Assert.assertEquals(result.getTotalItems(), expectedResults.getTotalItems());

		Collection<TagApi> resultElements = result.getElements();
		Collection<TagApi> expectedElements = expectedResults.getElements();

		Iterator<TagApi> it = expectedElements.iterator();
		for (TagApi actual : resultElements) {
			TagApi expected = it.next();
			AssertUtil.assertDTOEquals(actual, expected);
		}
	}
}
